import cx from 'classnames'

import { useMainContext } from '../context/MainContext'
import { Link } from '@/frame/components/Link'

import styles from './Breadcrumbs.module.scss'

type Props = {
  inHeader?: boolean
}

export type BreadcrumbT = {
  title: string
  href?: string
}

export const Breadcrumbs = ({ inHeader }: Props) => {
  const { breadcrumbs } = useMainContext()

  return (
    /*
      NOTE: The breadcrumbs class and the nav tag are used by the
      Lunr search scripts. The a tag generated by the Link is also used.
      If these change, please also change
      updating src/search/scripts/parse-page-sections-into-records.ts.
    */
    <nav
      data-testid={inHeader ? 'breadcrumbs-header' : 'breadcrumbs-in-article'}
      className={cx('f5 breadcrumbs', styles.breadcrumbs)}
      aria-label="Breadcrumb"
      data-container="breadcrumbs"
    >
      <ul>
        {Object.values(breadcrumbs)
          .filter(Boolean)
          .map((breadcrumb, i, arr) => {
            const title = `${breadcrumb.title}`
            return [
              !breadcrumb.href ? (
                <span data-testid="breadcrumb-title" key={title} className="px-2">
                  {breadcrumb.title}
                </span>
              ) : (
                <li className="d-inline-block" key={title}>
                  <Link
                    data-testid="breadcrumb-link"
                    href={breadcrumb.href}
                    title={title}
                    className={cx(
                      'Link--primary mr-2 color-fg-muted',
                      // Show the last breadcrumb if it's in the header, but not if it's in the article
                      // If there's only 1 breadcrumb, show it
                      !inHeader && i === arr.length - 1 && arr.length !== 1 && 'd-none',
                    )}
                  >
                    {breadcrumb.title}
                  </Link>
                  {i !== arr.length - 1 ? (
                    <span className="color-fg-muted pr-2" key={`${i}-slash`}>
                      /
                    </span>
                  ) : null}
                </li>
              ),
            ]
          })}
      </ul>
    </nav>
  )
}
